package com.easemob.helpdesk.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
//import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.easemob.helpdesk.bean.OwnerInfoRes;
import com.easemob.helpdesk.bean.OwnerLevelInfo;
import com.easemob.helpdesk.bean.TagBean;
import com.easemob.helpdesk.utils.CommonUtils;
import com.easemob.helpdesk.utils.DialogUtils;
import com.easemob.helpdesk.utils.DisplayUtil;
import com.easemob.helpdesk.widget.AutoNewLineLayout;
import com.easemob.helpdesk.widget.CircleImageView;
import com.housekeeperapp.R;
import com.net.ApiService;
import com.net.BaseResponse;
import com.net.HKHttpUtils;
import com.net.HKResponseResultCallBack;

import java.util.ArrayList;
import java.util.List;


import retrofit2.Call;

import static android.util.TypedValue.COMPLEX_UNIT_PX;

/**
 * Created by wsj on 2017/10/26.
 */
public class UserActivity extends BaseActivityV2 {
    private static final String TAG = "UserActivity";
    private static final int REQUEST_CODE_TAG = 1001;


    /**
     * 返回按钮
     */
    protected RelativeLayout rlBack;
    public CircleImageView imageView;
    public TextView owner_addr;
    public TextView owner_birthday;
    public TextView owner_name;
    // 电话按钮
    public ImageView owner_phone;
    //服务统计
    public TextView service_today;
    public TextView service_all;
    public TextView reward_count;

    // 评价标签个数
    public TextView flag_witty;

    public TextView flag_capable;

    public TextView flag_ardour;

    public TextView flag_intimate;

    // 评价列表
    public ListView evaluate_list;

    public LinearLayout star_l;

    public LinearLayout evaluate_container;

    @Override
    protected void initFindView() {
        rlBack=findViewById(R.id.rl_back);

        imageView=findViewById(R.id.owner_header);
        owner_addr=findViewById(R.id.owner_addr);
        owner_birthday=findViewById(R.id.owner_birthday);

        owner_name=findViewById(R.id.owner_name);
        owner_phone=findViewById(R.id.owner_phone);
        service_today=findViewById(R.id.service_today);
        service_all=findViewById(R.id.service_all);

        reward_count=findViewById(R.id.reward_count);
        flag_witty=findViewById(R.id.flag_witty);
        flag_capable=findViewById(R.id.flag_capable);
        flag_ardour=findViewById(R.id.flag_ardour);
        flag_intimate=findViewById(R.id.flag_intimate);
        evaluate_list=findViewById(R.id.evaluate_list);
        star_l=findViewById(R.id.star_l);
        evaluate_container=findViewById(R.id.evaluate_container);

        line=findViewById(R.id.line);
        empty_tag=findViewById(R.id.empty_tag);
        tag_wrapper=findViewById(R.id.tag_wrapper);
        titleText=findViewById(R.id.owner_view_name);

        tagTitle=findViewById(R.id.tag_title);
        totalEvaluateTitle=findViewById(R.id.total_evaluate_title);
        vipIcon=findViewById(R.id.vip_icon);
        level=findViewById(R.id.level);
        detailLevel=findViewById(R.id.detail_level);


        findViewById(R.id.add_owner_tag).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(UserActivity.this,TagsActivity.class);
                i.putExtra("OWNER_ID",ownerId);
                i.putExtra("levelKey",levelKey);
                i.putExtra("detailLevelKey",detailLevelKey);
                i.putExtra("levelValue", levelValue);
                i.putExtra("detailLevelValue",detailLevelValue);
                startActivityForResult(i,REQUEST_CODE_TAG);
            }
        });
        rlBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        owner_phone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+phone));
                startActivity(intent);
            }
        });



    }

    public View line;

    TextView empty_tag;

    AutoNewLineLayout tag_wrapper;
    TextView titleText;
    TextView tagTitle;
    TextView totalEvaluateTitle;
    ImageView vipIcon;
    TextView level;
    TextView detailLevel;

    String levelKey;
    String detailLevelKey;
    String levelValue;
    String detailLevelValue;



    /**
     * 加载提示Dialog
     */
    public Dialog pd = null;


    private List<OwnerInfoRes.DataBean.EvaluationListBean> mList;
    private StringAdapter mAdapter;

    private String wxname;
    private String phone;
    private long ownerId;

    retrofit2.Call<BaseResponse<OwnerInfoRes.DataBean>> callUserInfoData;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_user_info);
        initFindView();

        mList = new ArrayList<>();

        mAdapter = new StringAdapter();
        evaluate_list.setAdapter(mAdapter);

        titleText.setText(getResources().getString(R.string.HU_LI_ZHAN).equals(MainActivity.productKey)?"查看用户详情":"查看业主详情");
        tagTitle.setText(getResources().getString(R.string.HU_LI_ZHAN).equals(MainActivity.productKey)?"用户标签":"业主标签");
        totalEvaluateTitle.setText(getResources().getString(R.string.HU_LI_ZHAN).equals(MainActivity.productKey)?"用户对我的总评价":"业主对我的总评价");

        //获取Intent传过来的数据
        Intent intent = getIntent();
        ownerId = intent.getLongExtra("id", -1L);
        phone = intent.getStringExtra("phone");
        String wxHeader = intent.getStringExtra("wxHeader");
        String addr = intent.getStringExtra("homeAddress");
        String idcardNumber = intent.getStringExtra("idcardNumber");
        wxname = intent.getStringExtra("wxname");
        levelKey = intent.getStringExtra("level");
        detailLevelKey = intent.getStringExtra("detailLevel");








        String name = intent.getStringExtra("name");
        int isVip = intent.getIntExtra("isVip",0);
        if (isVip == 1){
            vipIcon.setVisibility(View.VISIBLE);
        }

        //后退
//        rlBack.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//            }
//        });

//        HDClient.getInstance().agentManager().getAgentList(true, new HDDataCallBack<List<AgentUser>>);

        //加载头像
        Glide.with(this).load(wxHeader)
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE).placeholder(R.drawable.default_agent_avatar).error(R.drawable.default_agent_avatar)
                .into(imageView);

        //设置用户信息
        owner_addr.setText(addr);
        //设置生日
        if(!TextUtils.isEmpty(idcardNumber)){
            String birthday = CommonUtils.getBirthByIdCard(idcardNumber);
            if(!TextUtils.isEmpty(birthday)){
                owner_birthday.setText("生日:" + birthday);
            }else{
                owner_birthday.setText("生日: --");
            }
        }else{
            owner_birthday.setText("生日: --");
        }

//        owner_phone.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                //用intent启动拨打电话
//                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+phone));
//                startActivity(intent);
//            }
//        });
        if(!TextUtils.isEmpty(name)){
            owner_name.setText(name);
        }

        initData();
        getTags();
        getOwnerLevel();

    }
/*
    @OnClick({R.id.add_owner_tag,R.id.rl_back,R.id.owner_phone})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.add_owner_tag:
                Intent i = new Intent(this,TagsActivity.class);
                i.putExtra("OWNER_ID",ownerId);
                i.putExtra("levelKey",levelKey);
                i.putExtra("detailLevelKey",detailLevelKey);
                i.putExtra("levelValue", levelValue);
                i.putExtra("detailLevelValue",detailLevelValue);
                startActivityForResult(i,REQUEST_CODE_TAG);
                break;
            case R.id.rl_back:
                finish();
                break;
            case R.id.owner_phone:
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+phone));
                startActivity(intent);
                break;
        }
    }*/

    private void initData() {
        Log.d(TAG, "initData: id="+ownerId);
        Log.d(TAG, "initData: ticket="+ MainActivity.ticket);
        Log.d(TAG, "initData: userId="+MainActivity.userId);
        ApiService apiService = HKHttpUtils.getApiService();
        if (callUserInfoData == null) {
            callUserInfoData = apiService.getOwnerServiceSummary(MainActivity.ticket, String.valueOf(MainActivity.userId), String.valueOf(ownerId));
        }
        callUserInfoData.enqueue(new HKResponseResultCallBack<OwnerInfoRes.DataBean>() {
            @Override
            public void onSuccess(OwnerInfoRes.DataBean dataBean) {
                hideLoading();


                service_today.setText(String.valueOf(dataBean.getService_today()));
                service_all.setText(String.valueOf(dataBean.getService_all()));
                reward_count.setText(String.valueOf(dataBean.getReward_price()));

                flag_witty.setText("机智  " + (dataBean.getFlag_witty() <= 999999 ? dataBean.getFlag_witty():"999999+"));
                flag_capable.setText("干练  " + (dataBean.getFlag_capable() <= 999999 ? dataBean.getFlag_capable():"999999+"));
                flag_ardour.setText("热情  " + (dataBean.getFlag_ardour() <= 999999 ? dataBean.getFlag_ardour() : "999999+"));
                flag_intimate.setText("贴心  " + (dataBean.getFlag_intimate() <= 999999 ? dataBean.getFlag_intimate() :"999999+"));


                //打分(1~5分)
                for (int i=1;i<=dataBean.getReward_score();i++){
                    ImageView image = (ImageView)star_l.getChildAt(i-1);
                    image.setImageResource(R.drawable.hk_star_active);
                }

                // 列表展示
                List<OwnerInfoRes.DataBean.EvaluationListBean> dataList = dataBean.getEvaluationList();
                if(dataList != null && dataList.size() != 0){
                    mList.clear();
                    mList.addAll(dataList);
                    mAdapter.notifyDataSetChanged();
//                            evaluate_list.measure(0,0);
//                            CommonUtils.setListViewHeightBasedOnChildren(evaluate_list);
                }else {
                    line.setVisibility(View.GONE);
                    evaluate_container.setVisibility(View.GONE);
                }

            }

            @Override
            public void onGetDataFailed(int cd, String msg) {
                hideLoading();
                Toast.makeText(UserActivity.this, msg, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailed(retrofit2.Call call, Throwable t) {
                hideLoading();
                Toast.makeText(UserActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void getOwnerLevel(){

        ApiService apiService = HKHttpUtils.getApiService();
        apiService.getOwnerLevel(MainActivity.ticket,String.valueOf(ownerId)).enqueue(new HKResponseResultCallBack<OwnerLevelInfo>() {
            @Override
            public void onSuccess(OwnerLevelInfo ownerLevelInfo) {
                if (ownerLevelInfo == null || ownerLevelInfo.getLevel() == null){
                    levelKey = "";
                    levelValue = "";
                    detailLevelKey = "";
                    detailLevelValue = "";
                    return;
                }
                levelKey = ownerLevelInfo.getLevel().getLevel();
                levelValue = ownerLevelInfo.getLevel().getDescribe();
                detailLevelKey = ownerLevelInfo.getDetailLevel().getLevel();
                detailLevelValue = ownerLevelInfo.getDetailLevel().getDescribe();

                level.setText(levelValue);
                detailLevel.setText(detailLevelValue);
            }

            @Override
            public void onGetDataFailed(int cd, String msg) {
                Toast.makeText(UserActivity.this, msg, Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onFailed(Call call, Throwable t) {
                Toast.makeText(UserActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();

            }
        });
    }

    private void getTags(){
        if (ownerId != -1){
            ApiService apiService = HKHttpUtils.getApiService();
            final int textSize = DisplayUtil.dip2px(UserActivity.this,12);
            final int padding = DisplayUtil.dip2px(UserActivity.this, 4);
            final int margin = DisplayUtil.dip2px(UserActivity.this,5);
            apiService.getTags(MainActivity.ticket,ownerId).enqueue(new HKResponseResultCallBack<List<TagBean>>() {
                @Override
                public void onSuccess(List<TagBean> tagBeans) {
                    if (tagBeans == null || tagBeans.size() == 0){
                        tag_wrapper.setVisibility(View.GONE);
                        empty_tag.setVisibility(View.VISIBLE);
                    }else {
                        tag_wrapper.removeAllViews();
                        for (int i = 0 ; i < tagBeans.size() ; i ++){
                            TextView tag = new TextView(UserActivity.this);
                            LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                            p.setMargins(margin,margin,margin,margin);
                            tag.setLayoutParams(p);
                            tag.setBackgroundResource(R.drawable.btn_bg_shape_hk);
                            tag.setTextColor(Color.parseColor("#565656"));
                            tag.setPadding(padding, padding, padding, padding);
                            tag.setTextSize(COMPLEX_UNIT_PX,textSize);
                            tag.setText(tagBeans.get(i).getTagName2());
                            tag_wrapper.addView(tag);
                        }
                        tag_wrapper.setVisibility(View.VISIBLE);
                        empty_tag.setVisibility(View.GONE);
                    }
                }

                @Override
                public void onGetDataFailed(int cd, String msg) {
                    Toast.makeText(UserActivity.this,msg,Toast.LENGTH_LONG).show();
                }

                @Override
                public void onFailed(retrofit2.Call call, Throwable t) {
                    Toast.makeText(UserActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
                }
            });
        }else {

        }
    }

    public void showLoading() {
        //显示登录提示对话框
        pd = DialogUtils.getLoadingDialog(this, "加载中...");
        pd.show();
    }

    public void hideLoading() {
        if(pd != null && pd.isShowing()){
            pd.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

//        if (unbinder != null){
//            unbinder.unbind();
//        }
    }

    @Override
    protected void onStop() {
        super.onStop();
//        if (callUserInfoData != null && !callUserInfoData.isCanceled()){
//            callUserInfoData.cancel();
//        }
    }

    /**
     * 适配器
     */
    private class StringAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public OwnerInfoRes.DataBean.EvaluationListBean getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = View.inflate(UserActivity.this, R.layout.item_evaluation, null);
            }

            TextView name = (TextView) convertView.findViewById(R.id.tv_name);
            TextView time = (TextView) convertView.findViewById(R.id.tv_time);
            TextView content = (TextView) convertView.findViewById(R.id.tv_content);

            if(!TextUtils.isEmpty(mList.get(position).getName())){
                name.setText(mList.get(position).getName());
            }else{
                if(!CommonUtils.isBlank(wxname)) {
                    name.setText(wxname);
                }else{
                    name.setText("");
                }
            }
            if(mList.get(position).getOrder_reward_time() != null && !mList.get(position).getOrder_reward_time().isEmpty()){
                time.setText(mList.get(position).getOrder_reward_time());
            }

            content.setText(mList.get(position).getReward_evaluate());


            return convertView;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_TAG && resultCode == RESULT_OK){
            getTags();
            getOwnerLevel();
        }
    }
}
